package deposit
library(tidyverse); library(ggplot2)
## Warning: package 'tidyverse' was built under R version 4.1.2
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.1.1     v forcats 0.5.1
## Warning: package 'ggplot2' was built under R version 4.1.2
## Warning: package 'tibble' was built under R version 4.1.2
## Warning: package 'tidyr' was built under R version 4.1.2
## Warning: package 'readr' was built under R version 4.1.2
## Warning: package 'purrr' was built under R version 4.1.2
## Warning: package 'dplyr' was built under R version 4.1.2
## Warning: package 'stringr' was built under R version 4.1.2
## Warning: package 'forcats' was built under R version 4.1.2
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(plotly); library(shiny)
## Warning: package 'plotly' was built under R version 4.1.3
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
## Warning: package 'shiny' was built under R version 4.1.2

ggplotly()

BeerPrice.csv Demo

BP = read.csv("https://raw.githubusercontent.com/nazzstat/DataVisualization/master/BeerPrices.csv")
  • baseline ggplot
ggplot(BP)+
  geom_point(aes(x = Year, y = Price.per.Ounce))

  • wrap baseline plot in ggplotly()
ggplotly(
  
  ggplot(BP)+
  geom_point(aes(x = Year, y = Price.per.Ounce))
  
)
  • customize popup labels
ggplotly(
  
  ggplot(BP)+
  geom_point(aes(x = Year, y = Price.per.Ounce,
                 text = paste("Team:", Team,
                              "<br>City:", City))),
  
  # dictate what shows up in the pop up
  tooltip = "text"
  
)
## Warning: Ignoring unknown aesthetics: text
  • Create Interactive Elements Based on Plotly Hover in Shiny
ui = fluidPage(
  plotlyOutput("plotly"),
  tableOutput("HoverTable")
)

server = function(input, output){
  
  output$plotly = renderPlotly(
    {
      ggplotly(
        ggplot(BP)+
          geom_point(aes(x = Year, y = Price.per.Ounce,
                         text = paste("Team:", Team,
                                      "<br>City:", City,
                                      "<br>Price per Beer:", Price))),
        tooltip = "text",
        source = "main"
      )
    }
  )
  
  output$HoverTable = renderTable(
    {
      eventdat = event_data("plotly_hover", source = "main")
      
      # default with no hover 
      if(is.null(eventdat) == T) return (NULL)
      
      # store the hover coordinates
      x = as.numeric(eventdat[["x"]])
      y = as.numeric(eventdat[["y"]])
      
      # use the coordinates for filtering
      BP %>%
        filter(Price.per.Ounce == y, Year == x)
      
    }
  )
  
}


shinyApp(ui, server)
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.

Shiny applications not supported in static R Markdown documents

Spotify Demo

oneD = read.csv("https://raw.githubusercontent.com/nazzstat/DataVisualization/master/one_direction.csv",stringsAsFactors=FALSE)
glimpse(oneD)
## Rows: 89
## Columns: 19
## $ acousticness     <dbl> 0.00900, 0.12600, 0.81100, 0.01770, 0.05420, 0.22500,~
## $ artists          <chr> "['One Direction']", "['One Direction']", "['One Dire~
## $ danceability     <dbl> 0.726, 0.514, 0.709, 0.637, 0.663, 0.600, 0.574, 0.65~
## $ duration_ms      <int> 199987, 200400, 219040, 182867, 200213, 245493, 23793~
## $ energy           <dbl> 0.787, 0.727, 0.220, 0.930, 0.857, 0.663, 0.329, 0.87~
## $ explicit         <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,~
## $ id               <chr> "4cluDES4hQEUhmXj6TXkSo", "6M31fPFCYB8Job3MCjjrDV", "~
## $ instrumentalness <dbl> 0.00e+00, 0.00e+00, 0.00e+00, 0.00e+00, 0.00e+00, 0.0~
## $ key              <int> 4, 0, 7, 4, 2, 3, 1, 1, 8, 6, 10, 0, 6, 2, 6, 0, 8, 1~
## $ liveness         <dbl> 0.0596, 0.0978, 0.1750, 0.4520, 0.1440, 0.1190, 0.098~
## $ loudness         <dbl> -2.494, -6.131, -11.856, -2.632, -2.160, -5.802, -6.8~
## $ mode             <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0,~
## $ name             <chr> "What Makes You Beautiful", "They Don't Know About Us~
## $ popularity       <int> 82, 78, 78, 74, 74, 82, 78, 76, 82, 80, 78, 80, 76, 7~
## $ release_date     <chr> "5/25/12", "11/12/12", "11/12/12", "11/12/12", "11/12~
## $ speechiness      <dbl> 0.0737, 0.0492, 0.0327, 0.0511, 0.0544, 0.0477, 0.027~
## $ tempo            <dbl> 124.990, 147.917, 110.076, 90.014, 126.039, 121.070, ~
## $ valence          <dbl> 0.888, 0.370, 0.530, 0.886, 0.931, 0.286, 0.356, 0.48~
## $ year             <int> 2012, 2012, 2012, 2012, 2012, 2013, 2013, 2013, 2014,~
ggplotly(
  ggplot(oneD)+
    geom_point(aes(x = tempo, y = danceability, color = popularity,
                   text = paste("Title:", name,
                                "<br>Artist:", artists,
                                "<br> Year:", year,
                                "<br>Popularity:", popularity)))+
    geom_smooth(aes(x = tempo, y = danceability), se = F, color = "black", lwd = 0.5)+
    scale_color_distiller("popularity", palette = "RdPu", direction = 1),
  tooltip = "text"
)
## Warning: Ignoring unknown aesthetics: text
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
  • Construct a shiny with ploty that display annual song popularity
ui = fluidPage(
  plotlyOutput("mainplot"),
  textOutput("test"),
  plotOutput("AnnualRank")
)

server = function(input, output){
  
  output$mainplot = renderPlotly(
    {
      ggplotly(
        ggplot(oneD)+
          geom_point(aes(x = tempo, y = danceability, color = popularity,
                         text = paste("Title:", name,
                                      "<br>Artist:", artists,
                                      "<br> Year:", year,
                                      "<br>Popularity:", popularity)))+
          geom_smooth(aes(x = tempo, y = danceability), 
                      se = F, color = "black", lwd = 0.5)+
          scale_color_distiller("popularity", palette = "RdPu",
                                direction = 1),
        tooltip = "text",
        source = "main"
      )
    }
  )
  output$AnnualRank = renderPlot({
    event_dat = event_data("plotly_hover", source = "main")
    
    # default
    if(is.null(event_dat) == T) return(NULL)
    
    
    
    oneD %>% 
      filter(danceability == as.numeric(event_dat[['y']]),
             tempo == as.numeric(event_dat[['x']])) %>%
      pull(year) -> YoI
    
    oneD %>% 
      filter(year == YoI) %>% 
      select(name, popularity) %>%
      arrange(desc(popularity)) %>%
      
    
    }
  })
}

shinyApp(ui, server)


plot_ly()

Demo

plot_ly(txhousing,
        x = ~listings,
        y = ~volume,
        z = ~year,
        color = ~median,
        size = ~median,
        type = "scatter3d", # type = c("box", "bar", "heatmap", "surface")
        mode = "markers",
        text = ~city,
        hoverinfo = "text")
## Warning: Ignoring 1426 observations
## Warning: `line.width` does not currently support multiple values.
txhousing %>% head()
## # A tibble: 6 x 9
##   city     year month sales   volume median listings inventory  date
##   <chr>   <int> <int> <dbl>    <dbl>  <dbl>    <dbl>     <dbl> <dbl>
## 1 Abilene  2000     1    72  5380000  71400      701       6.3 2000 
## 2 Abilene  2000     2    98  6505000  58700      746       6.6 2000.
## 3 Abilene  2000     3   130  9285000  58100      784       6.8 2000.
## 4 Abilene  2000     4    98  9730000  68600      785       6.9 2000.
## 5 Abilene  2000     5   141 10590000  67300      794       6.8 2000.
## 6 Abilene  2000     6   156 13910000  66900      780       6.6 2000.